<template>
  <n-modal v-model:show="showModal" preset="dialog" :show-icon="false">
    <n-card v-if="editType==='edit' || editType==='add'">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <flexform ref="flexFormref" :formList="formList" :formValue="formValue">
        <template #fengmian="{formitem}">
          <n-form-item  :path="formitem.path || formitem.key" :label="formitem.label"
                       :rule="formitem.rules||[]">
            <upimg ref="uploadref" :value="formValue.img"></upimg>
          </n-form-item>
        </template>
        <template #content="{formitem}">
          <n-form-item  :path="formitem.path || formitem.key" :label="formitem.label"
                        :rule="formitem.rules||[]">
            <raichTextEdit ref="raichTextEditref" :neirong="formValue.content"></raichTextEdit>
          </n-form-item>
        </template>
      </flexform>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">取消</n-button>
          <n-button @click="handleOK" type="primary">{{ formValue.id ? "编辑" : "创建" }}</n-button>
        </div>
      </template>
    </n-card>
<!--    查看-->
    <n-card v-if="editType==='view'">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <descriptions :infoList="_lanmulist">
        <template #img>
          <NAvatar v-if="formValue.img" size="small" :src="formValue.img"></NAvatar>
          <span v-else>无</span>
        </template>
        <template #content>
          <p v-html="formValue.content"></p>
        </template>
      </descriptions>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="clickEdit" type="primary">编辑</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
<!--    创建修改成功-->
    <n-card v-if="editType==='success'">
      <n-result status="success" title="成功" :description="formValue.id?'编辑成功':'创建成功'">
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
<!--    创建修改失败-->
    <n-card v-if="editType==='error'">
      <n-result status="error" title="错误" >
        <template>
          <p>{{ errortext }}</p>
        </template>
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="getreturn" type="primary">返回</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup name="Edit">
import {useRoute, useRouter} from "vue-router";
import http from "@/request/request"
import guiling from "../../../../util/guiling";
import {isObject} from "../../../../util/isObject";

const router = useRouter()
const route = useRoute()
const flexFormref = ref(null)   // 表单组件
const raichTextEditref = ref(null)   // 表单组件
const uploadref = ref(null)   // 表单组件
const showModal = ref(false)    // 模态框的显示
const title = ref("")         // 标题
const loading = ref(false)    // 加载状态
const editType = ref("add")   // 类型，编辑。新建、查看
const formValue = ref({})   // 表单数据
const formData = ref({})   // 描述列表数据
const errortext = ref("")   // 错误信息

const emit = defineEmits(["shuaxin"])
// 弹窗初始化
const init = (type, item = null) => {
  editType.value = type
  switch (type) {
    case "add":
      title.value = "新建"
      break;
    case "edit":
      title.value = "编辑"
      break;
    case "view":
      title.value = "详情"
      break;
  }
  if (item) {
    formData.value = item
    Object.keys(formData.value).forEach(item=>{
      if(isObject(formData.value[item])){
        formValue.value[item] = formData.value[item].id
      }else{
        formValue.value[item] = formData.value[item]
      }
    })

  }
  getzhuanlan()
  showModal.value = true
}
const doClose = () => {
  showModal.value = false
  emit("shuaxin")
  reset()
}
const reset = () => {
  formValue.value = guiling(formValue.value)
  formData.value = {}
  editType.value = ""
  title.value = ""
}
// 点击确定
const handleOK = () => {
  if (formValue.value.id) {
    flexFormref.value.jiaoyan(updatefunc)
  } else {
    flexFormref.value.jiaoyan(createfunc)
  }
}

// 创建的处理函数
const createfunc = (data) => {
  const neirong = raichTextEditref.value.getHtml()
  const img = uploadref.value.getimgurl()
  const jieguo = {...data,content:neirong,img}
  http.contentadd(jieguo).then(res => {
    if (res && res.data.code === 0) {
      getsuccess()
    } else {
      getfaild()
    }
  }).catch(() => {
    getfaild()
  })
}
// 编辑的处理函数
const updatefunc = (data) => {
  const neirong = raichTextEditref.value.getHtml()
  const img = uploadref.value.getimgurl()
  const jieguo = {...data,content:neirong,img}
  http.contentupdate(jieguo, formValue.value.id).then(res => {
    if (res && res.data.code === 0) {
      getsuccess()
    } else {
      getfaild(res.data)
    }
  }).catch((err) => {
    getfaild(err)
  })
}
// 表单配置
const formList = ref([
  {
    label: "博客标题",
    key: "name",
    type: "input",
    rules: [{required: true, message: "请输入博客标题", trigger: ["input", "change", "blur"]}, {
      max: 50,
      min: 2,
      message: "请输入2-50为的名称",
      trigger: ["input", "change", "blur"]
    },]
  },
  {
    label: "专栏名称",
    key: "lanmu",
    type: "select",
    options: [],
    rules: [{required: true, message: "请选择专栏", trigger: ["input", "change", "blur"]},]
  },
  {
    label: "封面",
    key: "fengmian",
    type:"slot",
    slot:"fengmian",
    rules: []
  },
  {
    label: "内容",
    key: "content",
    type:"slot",
    slot:"content",
    rules: [],
  },
])

// 交互成功
const getsuccess = () => {
  editType.value = "success"
  setTimeout(() => {
    doClose()
  }, 500)
}
// 交互失败
const getfaild = (jieguo) => {
  editType.value = "error"
  errortext.value = jieguo ? jieguo.toString() : null
}


// 显示相关的配置
const lanmulist = ref([
  {label: "博客标题", key: "name"},
  {label: "博客栏目", key: "lanmu",render: (data)=>{
    return data.name
    }},
  {label:"封面",key:"img",slot:"img"},
  {label:"内容",key:"content",slot:"content"},
])
const _lanmulist = computed(() => {
  return lanmulist.value.map(item => {
    return {...item, value: item.render ? item.render(formData.value[item.key]) : formData.value[item.key],}
  })
})
// 点击编辑按钮
const clickEdit = () => {
  editType.value = "edit"
  title.value = "编辑"
}
// 点击返回
const getreturn = () => {
  if (formValue.value.id) {
    editType.value = "edit"
    title.value = "编辑"
  } else {
    editType.value = "add"
    title.value = "创建"
  }
  errortext.value = ""
}
// 获取专栏列表
const getzhuanlan=()=>{
  http.lanmulist().then(res=>{
    if(res.data && res.data.code===0){
      const data = res.data.items.map(item=>{
        return {label:item.name,value:item.id}
      })
      formList.value.forEach(item=>{
        if(item.key==="lanmu"){
          item.options = data
        }
      })
    }
  })
}

// 抛出方法和属性
defineExpose({init, doClose, reset})

</script>

<style scoped>

</style>